package com.tjdx.projectsubmission.service.impl;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjdx.projectsubmission.common.Constant;
import com.tjdx.projectsubmission.db.entity.EventRecord;
import com.tjdx.projectsubmission.db.entity.Quarter;
import com.tjdx.projectsubmission.db.entity.User;
import com.tjdx.projectsubmission.db.mapper.EventRecordMapper;
import com.tjdx.projectsubmission.db.mapper.QuarterMapper;
import com.tjdx.projectsubmission.db.mapper.UserMapper;
import com.tjdx.projectsubmission.service.EventRecordService;
import com.tjdx.projectsubmission.vo.EventFromRespVo;
import com.tjdx.projectsubmission.vo.EventListRespVo;
import com.tjdx.projectsubmission.vo.EventSubReqVo;
import com.tjdx.projectsubmission.vo.R;
import com.tjdx.projectsubmission.vo.event.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class EventRecordServiceImpl extends ServiceImpl<EventRecordMapper, EventRecord> implements EventRecordService {
    @Autowired
    private EventRecordMapper eventRecordMapper;
    @Autowired
    private QuarterMapper quarterMapper;
    @Autowired
    private UserMapper userMapper;

    private final static String STORE_URL = "https://dev-env.wutongchain.com:49080/v2/tx/store?ledger=blkc2022";
    private final static String DETAIL_URL = " https://dev-env.wutongchain.com:49082/#/txts/txtsdetail?txhash=%s&chainkey=explorer_1&appliName=blkc2022&appliId=blkc2022";

    @Override
    public R fromEventRecordInfo(Integer roleId, String quarterId,String operate) {
        log.info("填报页数据查询接口 - 角色ID:[{}]  时间ID:[{}]  操作:[{}]", roleId, quarterId, operate);
        EventFromRespVo eventRespVo = new EventFromRespVo();
        List<EventVo> eventVoList = new ArrayList<>();
        QueryWrapper<EventRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("quarter_id", quarterId);
        //查询当前日期所有字段
        List<EventRecord> eventRecordList = eventRecordMapper.selectList(queryWrapper);


        if (eventRecordList != null && !eventRecordList.isEmpty()) {
            for (EventRecord eventRecord : eventRecordList) {

                String data = eventRecord.getData();
                if (StringUtils.isNotBlank(data) && !"null".equals(data)) {
                    String eventCode = eventRecord.getEventCode();
                    EventVo eventVo = toJavaClass(eventCode, data);
                    if (eventVo != null) {
                        eventVoList.add(eventVo);
                    }
                }
            }
        }

 /*       //工程部
        if (Constant.ROLE_SGB.equals(roleId)) {
            eventVoList.removeIf(eventVo -> !Arrays.asList(role1).contains(eventVo.getCode()));
        //安全部审核
        }else if (Constant.ROLE_AQB.equals(roleId) && Constant.OPERATE_SH.equals("2")) {
            eventVoList.removeIf(eventVo -> !Arrays.asList(role1).contains(eventVo.getCode()));
        }else {
            eventVoList = new ArrayList<>();
        }*/



        eventRespVo.setEventList(eventVoList);
        log.info("填报页数据查询接口 - 返回数据:[{}]", eventRespVo);
        return R.ok().data("data", eventRespVo);
    }


    String[] role1 = new String[]{Constant.ROLE_XN, Constant.ROLE_X13, Constant.ROLE_X22, Constant.ROLE_X4};
    String[] role2 = new String[]{Constant.ROLE_XN, Constant.ROLE_X13, Constant.ROLE_X22, Constant.ROLE_X4};

    private EventVo toJavaClass(String code, String data) {
        EventVo eventVo = new EventVo();
        switch (code) {
            case Constant.ROLE_XN:
                /*     return JSONObject.parseObject(data, EventXnVo.class);*/
                EventXnVo eventXnVo = JSONObject.parseObject(data, EventXnVo.class);
                if (eventXnVo == null){
                    return eventVo;
                }
                eventVo.setData(eventXnVo.getData());
                eventVo.setCode(eventXnVo.getCode());
                eventVo.setName(eventXnVo.getName());
                eventVo.setExamine(eventXnVo.getExamine());
                break;
            case Constant.ROLE_X4:
                /*       return JSONObject.parseObject(data, EventX4Vo.class);*/
                EventX4Vo eventX4Vo = JSONObject.parseObject(data, EventX4Vo.class);
                if (eventX4Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX4Vo.getData());
                eventVo.setCode(eventX4Vo.getCode());
                eventVo.setName(eventX4Vo.getName());
                eventVo.setExamine(eventX4Vo.getExamine());
                break;
            case Constant.ROLE_X13:
                /*             return JSONObject.parseObject(data, EventX13Vo.class);*/
                EventX13Vo eventX13Vo = JSONObject.parseObject(data, EventX13Vo.class);
                if (eventX13Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX13Vo.getData());
                eventVo.setCode(eventX13Vo.getCode());
                eventVo.setName(eventX13Vo.getName());
                eventVo.setExamine(eventX13Vo.getExamine());
                break;
            case Constant.ROLE_X22:
                /*   return JSONObject.parseObject(data, EventX22Vo.class);*/
                EventX22Vo eventX22Vo = JSONObject.parseObject(data, EventX22Vo.class);
                if (eventX22Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX22Vo.getData());
                eventVo.setCode(eventX22Vo.getCode());
                eventVo.setName(eventX22Vo.getName());
                eventVo.setExamine(eventX22Vo.getExamine());
                break;
            case Constant.ROLE_B2:
                EventB2Vo eventB2Vo = JSONObject.parseObject(data, EventB2Vo.class);
                if (eventB2Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventB2Vo.getData());
                eventVo.setCode(eventB2Vo.getCode());
                eventVo.setName(eventB2Vo.getName());
                eventVo.setExamine(eventB2Vo.getExamine());
                break;
            case Constant.ROLE_X20:
                EventX20Vo eventX20Vo = JSONObject.parseObject(data, EventX20Vo.class);
                if (eventX20Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX20Vo.getData());
                eventVo.setCode(eventX20Vo.getCode());
                eventVo.setName(eventX20Vo.getName());
                eventVo.setExamine(eventX20Vo.getExamine());
                break;
            case Constant.ROLE_X21:
                EventX21Vo eventX21Vo = JSONObject.parseObject(data, EventX21Vo.class);
                if (eventX21Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX21Vo.getData());
                eventVo.setCode(eventX21Vo.getCode());
                eventVo.setName(eventX21Vo.getName());
                eventVo.setExamine(eventX21Vo.getExamine());
                break;
            case Constant.ROLE_X23:
                EventX23Vo eventX23Vo = JSONObject.parseObject(data, EventX23Vo.class);
                if (eventX23Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX23Vo.getData());
                eventVo.setCode(eventX23Vo.getCode());
                eventVo.setName(eventX23Vo.getName());
                eventVo.setExamine(eventX23Vo.getExamine());
                break;
            case Constant.ROLE_X24:
                EventX24Vo eventX24Vo = JSONObject.parseObject(data, EventX24Vo.class);
                if (eventX24Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX24Vo.getData());
                eventVo.setCode(eventX24Vo.getCode());
                eventVo.setName(eventX24Vo.getName());
                eventVo.setExamine(eventX24Vo.getExamine());
                break;
            case Constant.ROLE_X26:
                EventX26Vo eventX26Vo = JSONObject.parseObject(data, EventX26Vo.class);
                if (eventX26Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX26Vo.getData());
                eventVo.setCode(eventX26Vo.getCode());
                eventVo.setName(eventX26Vo.getName());
                eventVo.setExamine(eventX26Vo.getExamine());
                break;
            case Constant.ROLE_B3:
                EventB3Vo eventB3Vo = JSONObject.parseObject(data, EventB3Vo.class);
                if (eventB3Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventB3Vo.getData());
                eventVo.setCode(eventB3Vo.getCode());
                eventVo.setName(eventB3Vo.getName());
                eventVo.setExamine(eventB3Vo.getExamine());
                break;
            case Constant.ROLE_B4:
                EventB4Vo eventB4Vo = JSONObject.parseObject(data, EventB4Vo.class);
                if (eventB4Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventB4Vo.getData());
                eventVo.setCode(eventB4Vo.getCode());
                eventVo.setName(eventB4Vo.getName());
                eventVo.setExamine(eventB4Vo.getExamine());
                break;
            case Constant.ROLE_E1:
                EventE1Vo eventE1Vo = JSONObject.parseObject(data, EventE1Vo.class);
                if (eventE1Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventE1Vo.getData());
                eventVo.setCode(eventE1Vo.getCode());
                eventVo.setName(eventE1Vo.getName());
                eventVo.setExamine(eventE1Vo.getExamine());
                break;
            case Constant.ROLE_X5:
                EventX5Vo eventX5Vo = JSONObject.parseObject(data, EventX5Vo.class);
                if (eventX5Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX5Vo.getData());
                eventVo.setCode(eventX5Vo.getCode());
                eventVo.setName(eventX5Vo.getName());
                eventVo.setExamine(eventX5Vo.getExamine());
                break;
            case Constant.ROLE_X14:
                EventX14Vo eventX14Vo = JSONObject.parseObject(data, EventX14Vo.class);
                if (eventX14Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX14Vo.getData());
                eventVo.setCode(eventX14Vo.getCode());
                eventVo.setName(eventX14Vo.getName());
                eventVo.setExamine(eventX14Vo.getExamine());
                break;
            case Constant.ROLE_X25:
                EventX25Vo eventX25Vo = JSONObject.parseObject(data, EventX25Vo.class);
                if (eventX25Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX25Vo.getData());
                eventVo.setCode(eventX25Vo.getCode());
                eventVo.setName(eventX25Vo.getName());
                eventVo.setExamine(eventX25Vo.getExamine());
                break;

            case Constant.ROLE_X7:
                EventX7Vo eventX7Vo = JSONObject.parseObject(data, EventX7Vo.class);
                if (eventX7Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX7Vo.getData());
                eventVo.setCode(eventX7Vo.getCode());
                eventVo.setName(eventX7Vo.getName());
                eventVo.setExamine(eventX7Vo.getExamine());
                break;
            case Constant.ROLE_X8:
                EventX8Vo eventX8Vo = JSONObject.parseObject(data, EventX8Vo.class);
                if (eventX8Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX8Vo.getData());
                eventVo.setCode(eventX8Vo.getCode());
                eventVo.setName(eventX8Vo.getName());
                eventVo.setExamine(eventX8Vo.getExamine());
                break;
            case Constant.ROLE_X9:
                EventX9Vo eventX9Vo = JSONObject.parseObject(data, EventX9Vo.class);
                if (eventX9Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX9Vo.getData());
                eventVo.setCode(eventX9Vo.getCode());
                eventVo.setName(eventX9Vo.getName());
                eventVo.setExamine(eventX9Vo.getExamine());
                break;
            case Constant.ROLE_X10:
                EventX10Vo eventX10Vo = JSONObject.parseObject(data, EventX10Vo.class);
                if (eventX10Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX10Vo.getData());
                eventVo.setCode(eventX10Vo.getCode());
                eventVo.setName(eventX10Vo.getName());
                eventVo.setExamine(eventX10Vo.getExamine());
                break;
            case Constant.ROLE_X11:
                EventX11Vo eventX11Vo = JSONObject.parseObject(data, EventX11Vo.class);
                if (eventX11Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX11Vo.getData());
                eventVo.setCode(eventX11Vo.getCode());
                eventVo.setName(eventX11Vo.getName());
                eventVo.setExamine(eventX11Vo.getExamine());
                break;
            case Constant.ROLE_X12:
                EventX12Vo eventX12Vo = JSONObject.parseObject(data, EventX12Vo.class);
                if (eventX12Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX12Vo.getData());
                eventVo.setCode(eventX12Vo.getCode());
                eventVo.setName(eventX12Vo.getName());
                eventVo.setExamine(eventX12Vo.getExamine());
                break;
            case Constant.ROLE_X16:
                EventX16Vo eventX16Vo = JSONObject.parseObject(data, EventX16Vo.class);
                if (eventX16Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX16Vo.getData());
                eventVo.setCode(eventX16Vo.getCode());
                eventVo.setName(eventX16Vo.getName());
                eventVo.setExamine(eventX16Vo.getExamine());
                break;
            case Constant.ROLE_X17:
                EventX17Vo eventX17Vo = JSONObject.parseObject(data, EventX17Vo.class);
                if (eventX17Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX17Vo.getData());
                eventVo.setCode(eventX17Vo.getCode());
                eventVo.setName(eventX17Vo.getName());
                eventVo.setExamine(eventX17Vo.getExamine());
                break;
            case Constant.ROLE_X27:
                EventX27Vo eventX27Vo = JSONObject.parseObject(data, EventX27Vo.class);
                if (eventX27Vo == null){
                    return eventVo;
                }
                eventVo.setData(eventX27Vo.getData());
                eventVo.setCode(eventX27Vo.getCode());
                eventVo.setName(eventX27Vo.getName());
                eventVo.setExamine(eventX27Vo.getExamine());
                break;
        }
        return eventVo;
    }


    private String toJsonString(String code, EventSubReqVo eventSubReqVo) {
        String data;
        switch (code) {
            case Constant.ROLE_XN:
                data = JSONObject.toJSONString(eventSubReqVo.getEventXnVo());
                break;
            case Constant.ROLE_X4:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX4Vo());
                break;
            case Constant.ROLE_X13:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX13Vo());
                break;
            case Constant.ROLE_X22:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX22Vo());
                break;
            case Constant.ROLE_B2:
                data = JSONObject.toJSONString(eventSubReqVo.getEventB2Vo());
                break;
            case Constant.ROLE_X20:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX20Vo());
                break;
            case Constant.ROLE_X21:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX21Vo());
                break;
            case Constant.ROLE_X23:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX23Vo());
                break;
            case Constant.ROLE_X24:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX24Vo());
                break;
            case Constant.ROLE_X26:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX26Vo());
                break;
            case Constant.ROLE_B3:
                data = JSONObject.toJSONString(eventSubReqVo.getEventB3Vo());
                break;
            case Constant.ROLE_B4:
                data = JSONObject.toJSONString(eventSubReqVo.getEventB4Vo());
                break;
            case Constant.ROLE_E1:
                data = JSONObject.toJSONString(eventSubReqVo.getEventE1Vo());
                break;
            case Constant.ROLE_X5:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX5Vo());
                break;
            case Constant.ROLE_X14:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX14Vo());
                break;
            case Constant.ROLE_X25:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX25Vo());
                break;
            case Constant.ROLE_X7:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX7Vo());
                break;
            case Constant.ROLE_X8:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX8Vo());
                break;
            case Constant.ROLE_X9:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX9Vo());
                break;
            case Constant.ROLE_X10:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX10Vo());
                break;
            case Constant.ROLE_X11:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX11Vo());
                break;
            case Constant.ROLE_X12:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX12Vo());
                break;

            case Constant.ROLE_X16:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX16Vo());
                break;
            case Constant.ROLE_X17:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX17Vo());
                break;
            case Constant.ROLE_X27:
                data = JSONObject.toJSONString(eventSubReqVo.getEventX27Vo());
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + code);
        }
        return data;
    }


    private String getEventName(String code, String defaultName) {
        String name = defaultName;
        switch (code) {
            case Constant.ROLE_XN:
                name = "关注事件：X1火花飞溅；X2残留焊渣/焊件；X3工人施工经验不足；X6电火花；X15人员发现火情不及时";
                break;
            case Constant.ROLE_X4:
                name = "关注事件：X4吸烟";
                break;
            case Constant.ROLE_X13:
                name = "关注事件：X13可燃物堆积";
                break;
            case Constant.ROLE_X22:
                name = "关注事件：X22现场人员密度过大";
                break;
            case Constant.ROLE_X20:
                name = "关注事件：X18人员未受消防训练；X19消防队不熟悉现场；X20消防演练不到位";
                break;
            case Constant.ROLE_X21:
                name = "关注事件：X21应急预案制定不到位";
                break;
            case Constant.ROLE_X23:
                name = "关注事件：X23逃生路线过长";
                break;
            case Constant.ROLE_X24:
                name = "关注事件：X24应急照明设备失效";
                break;
            case Constant.ROLE_X26:
                name = "关注事件：X26疏散标识失效";
                break;
            case Constant.ROLE_X5:
                name = "关注事件：X5为人放火";
                break;
            case Constant.ROLE_X14:
                name = "关注事件：X14防火间距不足";
                break;
            case Constant.ROLE_X25:
                name = "关注事件：X25安全出口堵塞";
                break;
            case Constant.ROLE_X7:
                name = "关注事件：X7违规铺设";
                break;
            case Constant.ROLE_X8:
                name = "关注事件：X8机械性损伤";
                break;
            case Constant.ROLE_X9:
                name = "关注事件：X9隧道渗水漏水";
                break;
            case Constant.ROLE_X10:
                name = "关注事件：X10外界摩擦";
                break;
            case Constant.ROLE_X11:
                name = "关注事件：X11接触不良";
                break;
            case Constant.ROLE_X12:
                name = "关注事件：X12过负荷";
                break;
            case Constant.ROLE_X16:
                name = "关注事件：X16火灾自动报警设备失效";
                break;
            case Constant.ROLE_X17:
                name = "关注事件：X17灭火设备不够/失效";
                break;
            case Constant.ROLE_X27:
                name = "关注事件：X27应急广播失效";
                break;
            default:
                name = defaultName;
        }
        return name;
    }


    @Override
    public R submitEventRecordInfo(@RequestBody EventSubReqVo eventSubReqVo) {
        log.info("填报页数据提交接口 - 请求参数:[{}]", eventSubReqVo.toString());
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Integer userId = (Integer)session.getAttribute("userId");
        String roleId = (String)session.getAttribute("roleId");
        String code = eventSubReqVo.getEventCode();
        String quarterId = eventSubReqVo.getQuarterId();
        String operate = eventSubReqVo.getOperate();
        if (StringUtils.isBlank(code) || StringUtils.isBlank(quarterId)){
            return R.error().message("参数错误");
        }
        QueryWrapper<EventRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("quarter_id", quarterId);
        queryWrapper.eq("event_code", code);
        List<EventRecord> eventRecordList = eventRecordMapper.selectList(queryWrapper);
        String data = toJsonString(code, eventSubReqVo);
        if (StringUtils.isBlank(data) || "null".equals(data)){
            return R.error().message("参数错误");
        }
        log.info("填报页数据提交接口 - data:[{}]", data);

        //区块链交易id
        String dataId = submitBlockchain(data);
        if (eventRecordList != null && !eventRecordList.isEmpty()) {
            //修改
            EventRecord eventRecord = eventRecordList.get(0);
            eventRecord.setData(data);
            eventRecord.setUpdateTime(new Date());
            eventRecord.setBlockHash(dataId);
            eventRecord.setUser2(userId!=null ? String.valueOf(userId) : null);
            eventRecord.setUser3(userId!=null ? String.valueOf(userId) : null);
            eventRecordMapper.updateById(eventRecord);
        } else {
            //新增
            EventRecord eventRecord = new EventRecord();
            eventRecord.setQuarterId(Integer.valueOf(quarterId));
            eventRecord.setEventName(getEventName(code,eventSubReqVo.getEventName()));
            eventRecord.setEventCode(code);
            eventRecord.setCreateTime(new Date());
            eventRecord.setUpdateTime(new Date());
            eventRecord.setEventType("1");
            eventRecord.setData(data);
            eventRecord.setBlockHash(dataId);
            eventRecord.setUser1(userId!=null ? String.valueOf(userId) : null);
            eventRecordMapper.insert(eventRecord);
        }
        return R.ok();
    }

    @Override
    public R
    eventRecordList(String quarterId) {
        QueryWrapper<Quarter> qw = new QueryWrapper<>();
        qw.orderByDesc("sort");
        List<Quarter> quarterList = quarterMapper.selectList(qw);
        Map<Integer, String> quarterMap = new HashMap<>();
        if (quarterList != null && !quarterList.isEmpty()) {
            quarterMap = quarterList.stream()
                    .collect(Collectors.toMap(Quarter::getId, Quarter::getName));
        }

        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        Map<Integer, User> userMap = new HashMap<>();
        if (userList != null && !userList.isEmpty()) {
            userMap = userList.stream()
                    .collect(Collectors.toMap(u -> u.getId(), u -> u));
        }

        QueryWrapper<EventRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("quarter_id", quarterId);
        queryWrapper.orderByDesc("create_time");
        List<EventRecord> eventRecordList = eventRecordMapper.selectList(queryWrapper);
        List<EventListRespVo> eventListRespVoList = new ArrayList<>();

        if (eventRecordList != null) {
            Map<Integer, String> finalQuarterMap = quarterMap;
            Map<Integer, User> finalUserMap = userMap;
            List<EventListRespVo> finalEventListRespVoList = eventListRespVoList;
            eventRecordList.forEach(eventRecord -> {
                EventListRespVo eventListRespVo = new EventListRespVo();
                BeanUtils.copyProperties(eventRecord, eventListRespVo);
                eventListRespVo.setQuarter(finalQuarterMap.get(eventRecord.getQuarterId()));
                eventListRespVo.setEventDesc("------");

                Integer user1 = StringUtils.isNotBlank(eventRecord.getUser1()) ? Integer.valueOf(eventRecord.getUser1()) : null;
                Integer user2 = StringUtils.isNotBlank(eventRecord.getUser2()) ?  Integer.valueOf(eventRecord.getUser2()): null;
                Integer user3 = StringUtils.isNotBlank(eventRecord.getUser3()) ? Integer.valueOf(eventRecord.getUser3()): null;

                if (user1!=null){
                    User userInfo = finalUserMap.get(user1);
                    if (userInfo != null) {
                        eventListRespVo.setFzr(userInfo.getLot() + "-(" + userInfo.getNickname()+")");
                    }
                }

                if (user2!=null && user3!=null) {
                    User userInfo2 = finalUserMap.get(user2);
                    User userInfo3 = finalUserMap.get(user3);
                    if (userInfo2 != null && userInfo3 != null) {
                        eventListRespVo.setShr(userInfo2.getLot() + "-(" + userInfo3.getNickname()+")" + "|" +
                                userInfo2.getLot() + "-(" + userInfo2.getNickname()+")");
                    } else if (userInfo2 != null) {
                        eventListRespVo.setShr(userInfo2.getLot() + "-(" + userInfo2.getNickname()+")");
                    } else if (userInfo3 != null) {
                        eventListRespVo.setShr(userInfo3.getLot() + "-(" + userInfo3.getNickname()+")");
                    }
                } else if (user2!=null) {
                    User userInfo2 = finalUserMap.get(user2);
                    if (userInfo2 != null) {
                        eventListRespVo.setShr(userInfo2.getLot() + "-(" + userInfo2.getNickname()+")");
                    }
                } else if (user3!=null) {
                    User userInfo3 = finalUserMap.get(user3);
                    if (userInfo3 != null) {
                        eventListRespVo.setShr(userInfo3.getLot() + "-(" + userInfo3.getNickname()+")");
                    }
                }
                //梧桐区块链详情页地址
                eventListRespVo.setBlockHashUrl(String.format(DETAIL_URL, eventRecord.getBlockHash()));
                eventListRespVo.setP(eventRecord.getOpinion1());
                eventListRespVo.setX(eventRecord.getOpinion2());
                finalEventListRespVoList.add(eventListRespVo);
            });
        }

        String x1,x2,x3,x6,x15,x18,x19,x20;
        Map<String,String> map = new HashMap<>(27);
        eventListRespVoList.forEach(eventListRespVo -> {
            String numStr = eventListRespVo.getEventCode().replaceAll("[^\\d]", "");
            eventListRespVo.setCodeNum(StringUtils.isNotBlank(numStr) ? Integer.parseInt(numStr) : 0);
        });
        eventListRespVoList = eventListRespVoList.stream().sorted(Comparator.comparing(EventListRespVo::getCodeNum)).collect(Collectors.toList());
        for (EventListRespVo eventListRespVo:eventListRespVoList){
            String code = eventListRespVo.getEventCode();
            String fen = eventListRespVo.getX();
            if (StringUtils.isNotBlank(fen)){
                if (code.equals(Constant.ROLE_XN)){
                    x1 = fen.split(",")[0];
                    x2 = fen.split(",")[1];
                    x3 = fen.split(",")[2];
                    x6 = fen.split(",")[3];
                    x15 = fen.split(",")[4];
                    map.put("X1",x1);
                    map.put("X2",x2);
                    map.put("X3",x3);
                    map.put("X6",x6);
                    map.put("X15",x15);
                }else if (code.equals(Constant.ROLE_X20)){
                    x18 = fen.split(",")[0];
                    x19 = fen.split(",")[1];
                    x20 = fen.split(",")[2];
                    map.put("X18",x18);
                    map.put("X19",x19);
                    map.put("X20",x20);
                }else {
                    map.put(code,fen.split(",")[0]);
                }
            }
        }

        String tValue,b1Value;
        double t = num(map.get("X1"), 1) * num(map.get("X2"), 1) * num(map.get("X3"), 1) * num(map.get("X4"), 1)
                * num(map.get("X5"), 1) * num(map.get("X6"), 1) * num(map.get("X7"), 1) * num(map.get("X8"), 1)
                * num(map.get("X9"), 1) * num(map.get("X10"), 1) * num(map.get("X11"), 1) * num(map.get("X12"), 1)
                + num(map.get("X13"), 0) + num(map.get("X14"), 0) + num(map.get("X15"), 0) * num(map.get("X16"), 1)
                * num(map.get("X17"), 1) * num(map.get("X18"), 1) * num(map.get("X19"), 1) + num(map.get("X20"), 0)
                * num(map.get("X21"), 1) + num(map.get("X22"), 0) * num(map.get("X23"), 1) * num(map.get("X24"), 1)
                * num(map.get("X25"), 1) * num(map.get("X26"), 1) * num(map.get("X27"), 1);

        String tLog = num(map.get("X1"), 1) +"*"+ num(map.get("X2"), 1) +"*"+ num(map.get("X3"), 1) +"*"+ num(map.get("X4"), 1)
                +"*"+ num(map.get("X5"), 1) +"*"+ num(map.get("X6"), 1) +"*"+ num(map.get("X7"), 1) +"*"+ num(map.get("X8"), 1)
                +"*"+ num(map.get("X9"), 1) +"*"+ num(map.get("X10"), 1) +"*"+ num(map.get("X11"), 1) +"*"+ num(map.get("X12"), 1)
                +"+"+ num(map.get("X13"), 0) +"+"+ num(map.get("X14"), 0) +"+"+ num(map.get("X15"), 0) +"*"+ num(map.get("X16"), 1)
                +"*"+ num(map.get("X17"), 1) +"*"+ num(map.get("X18"), 1) +"*"+ num(map.get("X19"), 1) +"+"+ num(map.get("X20"), 0)
                +"*"+ num(map.get("X21"), 1) +"+"+ num(map.get("X22"), 0) +"*"+ num(map.get("X23"), 1) +"*"+ num(map.get("X24"), 1)
                +"*"+ num(map.get("X25"), 1) +"*"+ num(map.get("X26"), 1) +"*"+ num(map.get("X27"), 1);

        double b1 = num(map.get("X1"), 1) * num(map.get("X2"), 1) * num(map.get("X3"), 1) * num(map.get("X4"), 1)
                * num(map.get("X5"), 1) * num(map.get("X6"), 1) * num(map.get("X7"), 1) * num(map.get("X8"), 1)
                * num(map.get("X9"), 1) * num(map.get("X10"), 1) * num(map.get("X11"), 1) * num(map.get("X12"), 1)
                + num(map.get("X13"), 0) + num(map.get("X14"), 0);

        String b1Log = num(map.get("X1"), 1) +"*"+ num(map.get("X2"), 1) +"*"+ num(map.get("X3"), 1) +"*"+ num(map.get("X4"), 1)
                +"*"+ num(map.get("X5"), 1) +"*"+ num(map.get("X6"), 1) +"*"+ num(map.get("X7"), 1) +"*"+ num(map.get("X8"), 1)
                +"*"+ num(map.get("X9"), 1) +"*"+ num(map.get("X10"), 1) +"*"+ num(map.get("X11"), 1) +"*"+ num(map.get("X12"), 1)
                +"+"+ num(map.get("X13"), 0) +"+"+ num(map.get("X14"), 0);

        if (t > 0.1) {
            tValue = "1";
        } else if (t >= 0.01) {
            tValue = "2";
        } else if (t >= 0.001) {
            tValue = "3";
        } else if (t >= 0.0001) {
            tValue = "4";
        } else {
            tValue = "5";
        }

        if (b1 > 0.1) {
            b1Value = "1";
        } else if (b1 >= 0.01) {
            b1Value = "2";
        } else if (b1 >= 0.001) {
            b1Value = "3";
        } else if (b1 >= 0.0001) {
            b1Value = "4";
        } else {
            b1Value = "5";
        }

        log.info("----------------------- T计算过程:{}",tLog);
        log.info("----------------------- B1计算过程:{}",b1Log);
        log.info("----------------------- T:{}  B1:{}", t, b1);

        eventListRespVoList.forEach(eventListRespVo -> {
            String numStr = eventListRespVo.getEventCode().replaceAll("[^\\d]", "");
            eventListRespVo.setCodeNum(StringUtils.isNotBlank(numStr) ? Integer.parseInt(numStr) : 0);
            eventListRespVo.setT(tValue);
            eventListRespVo.setB1(b1Value);
            eventListRespVo.setTValue(String.format("%.6f", t));
            eventListRespVo.setB1Value(String.format("%.6f", b1));
        });
        return R.ok().data("data", eventListRespVoList);
    }

    private Double num(String value,Integer num){
        if (StringUtils.isNotBlank(value)){
            return Double.parseDouble(value);
        }else {
            double num1 = num;
            return num1;
        }
    }

    /**
     * 数据上报到梧桐链
     */
    private String submitBlockchain(String data) {
        String dataId = null;
        Map<String, String> map = new HashMap<>();
        map.put("data", data);
        log.info("填报数据上报到梧桐链 - request:[{}]", JSONObject.toJSONString(map));
        String response = HttpUtil.post(STORE_URL, JSONObject.toJSONString(map));
        log.info("梧桐链response:[{}]", response);
        Map<String, Object> respMap = JSONObject.parseObject(response, Map.class);
        if (200==(int)respMap.get("state")) {
            dataId = (String) respMap.get("data");
        }
        return dataId;
    }

    @Override
    public R updateNumber(Integer id, String number) {
        EventRecord eventRecord = eventRecordMapper.selectById(id);
        String code = eventRecord.getEventCode();
        if (eventRecord !=null){
            eventRecord.setScore(number);
            this.compute(code,eventRecord);
            //计算
            eventRecordMapper.updateById(eventRecord);
        }
        return R.ok();
    }





    private EventRecord compute(String code, EventRecord eventRecord) {
        Double score = Double.parseDouble(eventRecord.getScore());
        Double standardNum = null;
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringStandardNum = new StringBuilder();
        switch (code) {
            case Constant.ROLE_XN:
                //x1
                standardNum = 0.022767463;
                stringStandardNum.append(standardNum);
                Double x1 = standardNum * ((11 - score) * (11 - score));
                //x2
                standardNum = 0.022767463;
                stringStandardNum.append(","+standardNum);
                Double x2 = standardNum * ((11 - score) * (11 - score));
                //x3
                standardNum = 0.005083997;
                stringStandardNum.append(","+standardNum);
                Double x3 = standardNum * ((11 - score) * (11 - score));
                //x6
                standardNum = 0.022767463;
                stringStandardNum.append(","+standardNum);
                Double x6 = standardNum * ((11 - score) * (11 - score));
                //x15
                standardNum = 0.005083997;
                stringStandardNum.append(","+standardNum);
                Double x15 = standardNum * ((11 - score) * (11 - score));
                stringBuilder.append(x1 > 1 ? 1 : x1);
                stringBuilder.append("," + (x2 > 1 ? 1 : x2));
                stringBuilder.append("," + (x3 > 1 ? 1 : x3));
                stringBuilder.append("," + (x6 > 1 ? 1 : x6));
                stringBuilder.append("," + (x15 > 1 ? 1 : x15));
                break;
            case Constant.ROLE_X4:
                standardNum = 0.005083997;
                break;
            case Constant.ROLE_X13:
                standardNum = 0.00397878;
                break;
            case Constant.ROLE_X22:
                standardNum = 0.00132626;
                break;
            case Constant.ROLE_B2:
                break;
            case Constant.ROLE_X20:
                //x18
                standardNum = 0.022767463;
                stringStandardNum.append(standardNum);
                Double x18 = standardNum * ((11 - score) * (11 - score));
                //x19
                standardNum = 0.002431477;
                stringStandardNum.append(","+standardNum);
                Double x19 = standardNum * ((11 - score) * (11 - score));
                //x20
                standardNum = 0.005083997;
                stringStandardNum.append(","+standardNum);
                Double x20 = standardNum * ((11 - score) * (11 - score));
                stringBuilder.append(x18>1 ? 1 : x18);

                stringBuilder.append("," + (x19>1 ? 1 : x19));
                stringBuilder.append("," + (x20>1 ? 1 : x20));
                break;
            case Constant.ROLE_X21:
                standardNum = 0.002431477;
                break;
            case Constant.ROLE_X23:
                standardNum = 0.000884173;
                break;
            case Constant.ROLE_X24:
                standardNum = 0.00198939;
                break;
            case Constant.ROLE_X26:
                standardNum = 0.007073386;
                break;
            case Constant.ROLE_X5:
                standardNum = 0.005083997;
                break;
            case Constant.ROLE_X14:
                standardNum = 0.00397878;
                break;
            case Constant.ROLE_X25:
                standardNum = 0.000884173;
                break;
            case Constant.ROLE_X7:
                standardNum = 0.043324492;
                break;
            case Constant.ROLE_X8:
                standardNum = 0.043324492;
                break;
            case Constant.ROLE_X9:
                standardNum = 0.002431477;
                break;
            case Constant.ROLE_X10:
                standardNum = 0.006410256;
                break;
            case Constant.ROLE_X11:
                standardNum = 0.043324492;
                break;
            case Constant.ROLE_X12:
                standardNum = 0.043324492;
                break;
            case Constant.ROLE_X16:
                standardNum = 0.002431477;
                break;
            case Constant.ROLE_X17:
                standardNum = 0.029619806;
                break;
            case Constant.ROLE_X27:
                standardNum = 0.002431477;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + code);
        }
        if (stringBuilder == null || "".equals(stringBuilder.toString())) {
            stringStandardNum.append(standardNum);
            double v = standardNum * ((11 - score) * (11 - score));
            stringBuilder.append(v > 1 ? 1 : v);
        }
        eventRecord.setOpinion1(stringStandardNum.toString());
        eventRecord.setOpinion2(stringBuilder.toString());
        return eventRecord;
    }
}
